﻿using System;
using System.Text;
using System.Windows.Forms;
using QAToolsAddin.Components;
using Excel = Microsoft.Office.Interop.Excel;

namespace QAToolsAddin.GenericDialogs {
    public partial class FrmException : ExcelForm {
        bool _expended = true;
        const string Padleft = "   ";

        public FrmException(Excel.Application excelapp, Exception exception)
            : base(excelapp) {
            InitializeComponent();
            var text = new StringBuilder();
            var ex = exception;
            do {
                text.AppendLine(ex.Message);
                text.AppendLine(ex.StackTrace);
                foreach (object value in exception.Data.Values) {
                    if (value != null)
                        text.AppendLine(Padleft + value.ToString());
                }
                text.AppendLine(string.Empty);
                ex = ex.InnerException;
            } while (ex != null);

            textBox1.Text = text.ToString();
            textBox1.KeyDown += textBox1_KeyDown;
        }

        private void FrmException_Load(object sender, EventArgs e) {
            ToggleDetails();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.A && e.Control) {
                textBox1.SelectAll();
                e.Handled = true;
            }
        }

        private void btDetails_Click(object sender, EventArgs e) {
            ToggleDetails();
        }

        private void ToggleDetails() {
            if (_expended) {
                _expended = false;
                textBox1.Visible = false;
                Height = (Height - ClientSize.Height) + textBox1.Location.Y;
            } else {
                _expended = true;
                textBox1.Visible = true;
                Height = (Height - ClientSize.Height) + textBox1.Location.Y + textBox1.Size.Height + textBox1.Location.X;
            }
        }

        private void btClose_Click(object sender, EventArgs e) {
            Close();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            System.Diagnostics.Process.Start(((LinkLabel)sender).Text);
        }
    }
}
